package com.cj.service;

import com.cj.dao.UserDao;
import com.cj.entity.PageBean;
import com.cj.entity.User;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class UserService {
    UserDao dao = new UserDao();
    public User checkLogin(String username, String password) {
        return dao.getEntity("select * from user where username=? and password=?", User.class, username, password);
    }

    public PageBean<User> findByPage(String currentPage, String pageSize, String name) {
        int cPage = Integer.parseInt(currentPage);
        int size = Integer.parseInt(pageSize);

        PageBean<User> pb = new PageBean();
        pb.setCurrentPage(cPage);
        pb.setPageSize(size);

        StringBuilder sql = new StringBuilder("select * from user where 1=1 ");
//        创建集合存储参数
        ArrayList<Object> list = new ArrayList<>();
        if(name!=null && "".equals(name.trim())){
            sql.append("and name like ?");
            list.add("%"+name+"%");
        }

        List<User> userList = dao.getEntities(sql.toString(), User.class, list.toArray());
        int totalCount =userList.size();
        pb.setTotalCount(totalCount);
        int totalPage = totalCount%size==0? totalCount/size : totalCount/size +1;
        pb.setTotalPage(totalPage);

//        数据
        sql.append("limit ?,?");
        list.add((cPage-1)*size);
        list.add(size);

         userList = dao.getEntities(sql.toString(), User.class, list.toArray());
         pb.setList(userList);
         return pb;
    }

    public int insertUser(User u) {
        String sql = "insert into user values(null,?,?,?,?,?,?,?,?,?,?)";
        return dao.update(sql, u.getName(),u.getPhone(),u.getAge(),u.getSex(),u.getUsername()
        ,u.getPassword(),u.getStatus(),new Date(),u.getRole(),u.getPicture());
    }

//
    public int deleteUser(String uids) {
        String sql ="delete from user where uid in ("+uids+")";
        return dao.update(sql);
    }

    public int updateUser(User u) {
        String  sql ="update user set name=?,phone=?,age=?,sex=?,username=?,password=?,status=?,createtime=?,role=?,picture=?  where uid=?";
        return dao.update(sql, u.getName(),u.getPhone(),u.getAge(),u.getSex(),u.getUsername()
                ,u.getPassword(),u.getStatus(),new Date(),u.getRole(),u.getPicture(),u.getUid());
    }






//    -------------------------------------------------------------------------------------------
//    ----------------------前台------------------------------------------
//
    public User checkPhone(String phone) {
        String sql="select * from user where phone =?";
        return dao.getEntity(sql, User.class,phone);
    }


    public User loginWeb(String phone, String password) {
        String sql ="select * from user where phone=? and password=?";
        return dao.getEntity(sql, User.class, phone, password);
    }
}
